/**
 * Created with IntelliJ IDEA.
 * Description:
 * User: 九转苍翎
 * Date: 2025/11/15
 * Time: 02:35
 */
public class Solution {
    public ListNode reverseKGroup(ListNode head, int k) {
        ListNode lengthNode = head;
        int length = 0;
        while(lengthNode != null){
            length++;
            lengthNode = lengthNode.next;
        }
        ListNode dummy = new ListNode(-1,head);
        ListNode p0 = dummy;
        ListNode pre = null;
        ListNode cur = p0.next;
        while(length >= k){
            length -= k;
            for(int i = 0;i < k;i++){
                ListNode next = cur.next;
                cur.next = pre;
                pre = cur;
                cur = next;
            }
            ListNode temp = p0.next;
            p0.next.next = cur;
            p0.next = pre;
            p0 = temp;
        }
        return dummy.next;
    }
}
